import json

import requests
from django.http import HttpResponse
from django.shortcuts import render
from django.views.decorators.http import require_http_methods

import mutils.logistic as lo
from mutils.SEIR import *

h = {
	'Accept': 'application/json',
	'Content-Type': 'application/json;charset=utf-8',
	'Referer': 'https://ncov.dxy.cn/ncovh5/view/pneumonia',
	'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36 Edg/84.0.522.49'
}
u = 'https://file1.dxycdn.com/2020/0801/201/4814471819137097243-135.json?t=26604489'
china_data = requests.get(u, h).json()['data']

# region ===utils===
def get_china_curves():
	ls = list(fitting())
	e = []
	for d, v in zip(range(195), ls):
		e.append({
			'date': int(d),
			'value': float(v),
			'type': '拟合预测'
		})
	for d, v in zip(range(195), china_data):
		e.append({
			'date': d,
			'value': v['currentConfirmedCount'],
			'type': '实际现存'})  # n0
	return e


def get_usa_curves():
	u = 'https://file1.dxycdn.com/2020/0315/553/3402160512808052518-135.json?t=26605341'
	usa_data = requests.get(u, h).json()['data']
	ls = list(lo.fitting())
	e = []
	for d, v in zip(range(188), ls):
		e.append({
			'date': int(d),
			'value': float(v),
			'type': '拟合预测'
		})
	for d, v in zip(range(188), usa_data):
		e.append({
			'date': d,
			'value': v['confirmedCount'],
			'type': '实际现存'})  # n0
	return e
# endregion

# region === DJG APIs ===
# 返回某一个点的预测值
@require_http_methods(['GET'])
def pre_test(request):
	x = int(request.GET.get('pre'))
	s = str(get_pre(x))
	return HttpResponse(json.dumps(s), content_type='application/json')


# 返回一组x:y坐标点，用于绘制预测曲线
@require_http_methods(['GET'])
def china_prediction(request):
	dic = get_china_curves()
	return HttpResponse(json.dumps(dic), content_type='application/json')


@require_http_methods(['GET'])
def usa_prediction(request):
	dic = get_usa_curves()
	return HttpResponse(json.dumps(dic), content_type='application/json')


@require_http_methods(['GET'])
def get_provinces(request):
	from DjangoAPI.for_views import getData, getSpecial
	from datetime import datetime
	m = request.GET.get('m')
	data = getData()
	# 要返回的json数据
	month_dict = {}
	for month in range(2, datetime.now().month):
		month_dict[f'{month}月'] = []
		# 按31天计算（getSpecial中有纠正日期功能）
		day = 31
		nowDate = f'{month}.{day}'
		# 找当前的日期下的各个省份的数据
		confirm_num = getSpecial(data, nowDate, '确诊')
		cured_num = getSpecial(data, nowDate, '治愈')
		death_num = getSpecial(data, nowDate, '死亡')
		for prov, val in confirm_num.items():
			value = confirm_num[prov] - cured_num[prov] - death_num[prov]
			month_dict[f'{month}月'].append({'name': prov, 'value': value})
	return HttpResponse(json.dumps(month_dict[f'{m}月'], ensure_ascii=False))


@require_http_methods(['GET'])
def get_china(request):
	c0 = []
	#  region ===values===
	for x, e in zip(range(1, 195), china_data):
		# c0.append({'date': x, 'type': '新增确诊', 'value': e['confirmedIncr']})  # ci
		c0.append({'date': x, 'type': '确诊总数', 'value': e['confirmedCount']})
		# c0.append({'date': x, 'type': '新增治愈', 'value': e['curedIncr']})  # zi
		c0.append({'date': x, 'type': '治愈总数', 'value': e['curedCount']})  # z0
		# c0.append({'date': x, 'type': '新增现存', 'value': e['currentConfirmedIncr']})  # ni
		c0.append({'date': x, 'type': '现存确诊', 'value': e['currentConfirmedCount']})  # n0
		# c0.append({'date': x, 'type': '新增死亡', 'value': e['deadIncr']})  # di
		c0.append({'date': x, 'type': '死亡总数', 'value': e['deadCount']})  # d0
		# c0.append({'date': x, 'type': '新增疑似', 'value': e['suspectedCountIncr']})  # si
		c0.append({'date': x, 'type': '疑似总数', 'value': e['suspectedCount']})  # s0
	#  endregion
	return HttpResponse(json.dumps(c0), content_type='application/json')


# 美国数据
@require_http_methods(['GET'])
def get_usa(request):
	h = {
		'Host': 'api.inews.qq.com',
		'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML'
					  ', like Gecko) Chrome/84.0.4147.105 Safari/537.36 Edg/84.0.522.49'
	}
	uu = 'https://api.inews.qq.com/newsqa/v1/automation/foreign/daily/list?country=美国&'
	data = requests.get(uu, h).json()['data']
	res = []
	for x, e in zip(range(1, 187), data):
		res.append({'date': x, 'type': '确诊', 'value': e['confirm']})
		res.append({'date': x, 'type': '治愈', 'value': e['heal']})
		res.append({'date': x, 'type': '死亡', 'value': e['dead']})
		res.append({'date': x, 'type': '新增', 'value': e['confirm_add']})
		res.append({'date': x, 'type': '现存', 'value': e['confirm'] - e['heal']})
	return HttpResponse(json.dumps(res))


@require_http_methods(['GET'])
def get_continent(request):
	r = []
	rsp = requests.get('https://api.inews.qq.com/newsqa/v1/automation/modules/list?modules=FAutoContinentStatis').json()
	d = rsp['data']['FAutoContinentStatis']
	ld = len(d)
	for i, e in zip(range(ld), d):
		r.append({'name': 'root', 'children': [{'name': k, 'value': v} for k, v in e['statis'].items()]})
	return HttpResponse(json.dumps(r), content_type='application/json')


@require_http_methods(['GET'])
def get_range(request):
	r = []
	u = "https://api.inews.qq.com/newsqa/v1/automation/modules/list?modules=FAutoCountryConfirmAdd"
	# 请求头，作用：伪装成浏览器反爬虫（虽然这个链接就是用来爬的）
	h = {
		'user-agent': 'User-Agent: Mozilla/5.0 (Windows NT 10.0 Win64 x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36',
	}
	d = requests.get(u, h).json()['data']['FAutoCountryConfirmAdd']
	ld = len(d)
	for i, e in zip(range(ld), d):
		r.append({'index': i, 'value': e['date']})
	return HttpResponse(json.dumps(r), content_type='application/json')


# @require_http_methods(["GET"])
def get_contries(request):
	u = "https://api.inews.qq.com/newsqa/v1/automation/modules/list?modules=FAutoCountryConfirmAdd"
	# 请求头，作用：伪装成浏览器反爬虫（虽然这个链接就是用来爬的）
	h = {
		'user-agent': 'User-Agent: Mozilla/5.0 (Windows NT 10.0 Win64 x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36',
	}
	d = requests.get(u, h).json()['data']['FAutoCountryConfirmAdd']
	ld = len(d)
	r = {'name': 'root', 'children': [{'name': k, 'value': v} for k, v in d.items() if v > 1000]}
	return HttpResponse(json.dumps(r), content_type='application/json')


# endregion

# region handles
def handle(request):
	err_info = '假装有错误信息'
	return render(request, 'error.html', {'info': err_info})


def handle4x(request, exce):
	err_info = '假装有错误信息'
	return render(request, 'error.html', {'info': err_info})


# endregion

if __name__ == '__main__':
	get_contries(None)
